package com.example.yls.demoa;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements IOnTimeChangeListener{
    private HighPriorityReceiver highPriorityReceiver;
    private LowPriorityReceiver lowPriorityReceiver;
    private MidllPriorityReceiver midllPriorityReceiver;
    private TimeReceiver receiver;
    private TextView txtTiem;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPrrorityReceiver();
        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("ORDERED_BROADCAST");
                intent.putExtra("Action","party");
                sendOrderedBroadcast(intent,null);
            }
        });

        receiver = new TimeReceiver(MainActivity.this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        registerReceiver(receiver,intentFilter);
        txtTiem = findViewById(R.id.time_view);
        updateTime();

    }




    //注册的三个有序接收者
    private void initPrrorityReceiver() {
        highPriorityReceiver = new HighPriorityReceiver();
        IntentFilter highFilter = new IntentFilter();
        highFilter.addAction("ORDERED_BROADCAST");
        highFilter.setPriority(100);
        registerReceiver(highPriorityReceiver,highFilter);

        lowPriorityReceiver = new LowPriorityReceiver();
        IntentFilter lowFilter = new IntentFilter();
        highFilter.addAction("ORDERED_BROADCAST");
        highFilter.setPriority(90);
        registerReceiver(lowPriorityReceiver,highFilter);

        midllPriorityReceiver = new MidllPriorityReceiver();
        IntentFilter midllFilter = new IntentFilter();
        highFilter.addAction("ORDERED_BROADCAST");
        highFilter.setPriority(80);
        registerReceiver(midllPriorityReceiver,highFilter);

    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(highPriorityReceiver);
        unregisterReceiver(lowPriorityReceiver);
        unregisterReceiver(midllPriorityReceiver);
        super.onDestroy();
    }


    @Override
    public void updateTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = simpleDateFormat.format(date);
        txtTiem.setText(time);
    }
}
